package cn.sfa.controller.users;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.login.LoginService;


/**
 * 
* 类名称：UsersController   
* 类描述： 用户管理处理类
* 创建人：LLY   
* 创建时间：2012-2-14   
* 修改人：LLY   
* 修改时间：2012-2-14   
* 修改备注：   
* @version
 */
@Controller
@RequestMapping("manage/user/index")
public class UsersController extends WebInitBinderContoller{

	Logger log = LoggerFactory.getLogger(UsersController.class);
	@Autowired
	LoginService loginService;
	
	//判断是否是代理人
	public boolean isAgent(HttpServletRequest request)
	{
		SaleUsersLogin saleUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		if(saleUser.getUserType().equals("USERTYPE_1"))
			return true;
		return false;
	}
	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		
		return this.getUers(request, response, map);
	}
	
	@RequestMapping("/adduser")
	public String addUser(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		if(isAgent(request))
		{
		return "users/adduser";
		}
		return "users/nopri";
	}
	/**
	 * 添加助理
	 * @param saleUser
	 * @param map
	 * @param request
	 * @return
	 * @throws  Exception 
	 */
	@RequestMapping("/add")
	public void add(SaleUsersLogin saleUser,ModelMap map,HttpServletRequest request,HttpServletResponse response) throws  Exception
	{
		String loginName=saleUser.getLoginName();
		String password=saleUser.getUserPassword();
		String password2=request.getParameter("userPassword2");
		String username=saleUser.getUserName();
		String email=saleUser.getEmail();
		String contactMobile=saleUser.getContactMobile();
		map.put("adduser", saleUser);//用于回显数据
		map.put("userPassword2Form", password2);//用于回显数据
		
		String msg="";
		int count=0;
		//表单验证
		if(loginName==null || "".equals(loginName))
		{
			msg="用户名不能为空！";
			count=count+1;
		}else if(password==null || "".equals(password))
		{
			msg= "密码不能为空！";
			count=count+1;
		}else if(password2==null || "".equals(password2))
		{
			msg="确认密码不能为空！";
			count=count+1;
		}else if(username==null || "".equals(username))
		{
			msg="用户姓名不能为空！";
			count=count+1;
		} else if(loginName.length()<5 || loginName.length()>16)
		{
			msg="用户名长度必须在5到16位";
			count=count+1;
		} else if(password.length()<7 || password.length()>14)
		{
			msg="密码长度必须在7到14位";
			count=count+1;
		} 
		else if(password2.length()<7 || password2.length()>14)
		{
			msg="确认密码长度必须在7到14位";
			count=count+1;
		}else if(!password2.equals(password))
		{
			msg="与密码不一致！";
			count=count+1;
		}
		else if(!CommonUtil.isEmpty(contactMobile) && !FormValidate.isMobileNumber(contactMobile))
		{
			msg="手机号码格式不正确！如：189XXXXXXXX";
			count=count+1;
		}else if(saleUser.getEmail()==null || "".equals(saleUser.getEmail()))
		{
			msg= "电子邮件不能为空！";
			count=count+1;
		}else if(!FormValidate.isMail(email))
		{
			msg="电子邮件格式不正确";
			count=count+1;
		}else if(loginService.existsEmail(null, email))
		{
			msg="此邮箱已经被注册，请更换其它邮箱";
			count=count+1;
		}
		
		boolean result=count==0;
		boolean flag=false;
		if(result)
		{
		//设置SaleUsersLogin用户属性
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		saleUser.setCreateUid(user.getSaleUsersLoginId());
		saleUser.setCreateDate(new Date());
		saleUser.setUpdateId(user.getSaleUsersLoginId());
		saleUser.setUpdateDate(new Date());
		saleUser.setUserStatus("y");//表示开启用户
		saleUser.setUserType("USERTYPE_2");//助理
		saleUser.setBranchId(user.getBranchId());
		saleUser.setIsAnonymous("n");//是否匿名
		saleUser.setLastPwdChangeDate(new Date());
		saleUser.setSendMailDate(new Date());
		saleUser.setUserAgentId(user.getUserAgentId());
		
		 
				//添加USER表用户
				flag=loginService.addUser(saleUser);
				if(flag)
				{
					msg="用户成功添加！";
					 
					 
				}else 
				{
					msg="用户添加失败！";
				}
		}
				
				response.setCharacterEncoding("UTF-8");
		        response.setContentType("application/json");
		        request.setCharacterEncoding("UTF-8");
		 
		            JSONObject temp = new JSONObject();
		             
		            temp.put("msg",msg);
		            temp.put("flag", flag);
		            temp.put("result",result);
		            
		            PrintWriter out=response.getWriter();
			        out.print(temp.toString());
					out.flush();
					out.close();
		 
	}
	@RequestMapping("/getusers")
	public String getUers(HttpServletRequest request,HttpServletResponse response,ModelMap map){


		List saleUsers=new ArrayList();
		String agentid=(String)request.getSession().getAttribute("agentid");
		saleUsers=loginService.allUsers(agentid);
		

		SaleUsersLogin curUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		saleUsers=loginService.allUsers(curUser.getSaleUsersLoginId());
		
		
		List<Object> adUsers=new ArrayList<Object>();
		for(int i=0;i<saleUsers.size();i++)
		{
			Map<String,String> mapTemp = new HashMap<String,String>();
			mapTemp = (Map<String,String>)saleUsers.get(i);
			String usertype=mapTemp.get("USERTYPE");
		}
		request.setAttribute("users",adUsers);
		return "users/getusers";
	}
	
	@RequestMapping("/update")
	public void update(ModelMap map,HttpServletRequest request,HttpServletResponse response,SaleUsersLogin saleUser) throws IOException
	{

		String loginName=saleUser.getLoginName();
		String password=saleUser.getUserPassword();
		String username=saleUser.getUserName();
		String email=saleUser.getEmail();
		String contactMobile=saleUser.getContactMobile();
		
		String msg="";
		int count=0;
		//表单验证
		if(loginName==null || "".equals(loginName))
		{
			msg="用户名不能为空！";
			count=count+1;
		}else if(password==null || "".equals(password))
		{
			msg= "密码不能为空！";
			count=count+1;
		} else if(username==null || "".equals(username))
		{
			msg="用户姓名不能为空！";
			count=count+1;
		} else if(loginName.length()<5 || loginName.length()>16)
		{
			msg="用户名长度必须在5到16位";
			count=count+1;
		} else if(password.length()<7 || password.length()>14)
		{
			msg="密码长度必须在7到14位";
			count=count+1;
		} 
		 
		else if(!CommonUtil.isEmpty(contactMobile) && !FormValidate.isMobileNumber(contactMobile))
		{
			msg="手机号码格式不正确！如：189XXXXXXXX";
			count=count+1;
		}else if(saleUser.getEmail()==null || "".equals(saleUser.getEmail()))
		{
			msg= "电子邮件不能为空！";
			count=count+1;
		}else if(!FormValidate.isMail(email))
		{
			msg="电子邮件格式不正确";
			count=count+1;
		}else if(loginService.existsEmail(saleUser.getSaleUsersLoginId(), email))
		{
			msg="此邮箱已经被注册，请更换其它邮箱";
			count=count+1;
		}
		boolean result=count==0;
		boolean flag=false;
		if(isAgent(request) || !CommonUtil.isEmpty(loginName))
		{
		
			
			if(result)
			{
				//设置SaleUsersLogin用户属性
				SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
				saleUser.setUpdateId(user.getSaleUsersLoginId());
				saleUser.setUpdateDate(new Date());
				saleUser.setUserStatus("y");//表示开启用户
				saleUser.setUserType("USERTYPE_2");//助理
				saleUser.setBranchId(user.getBranchId());
				saleUser.setIsAnonymous("n");//是否匿名
				saleUser.setLastPwdChangeDate(new Date());
				saleUser.setSendMailDate(new Date());
				saleUser.setUserAgentId(user.getUserAgentId());
				
				 
						//修改USER表用户
						flag=loginService.updateUserInfo(saleUser);
						if(flag)
						{
							msg="用户修改成功！";
							 
							 
						}else 
						{
							msg="用户修改失败！";
						}
			}
					
					
		}else
		{
			msg="对不起，你不是管理员，没有权限";
		}
			
			response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/json");
	        request.setCharacterEncoding("UTF-8");
	 
	            JSONObject temp = new JSONObject();
	             
	            temp.put("msg",msg);
	            temp.put("flag", flag);
	            temp.put("result",result);
	            
	            PrintWriter out=response.getWriter();
		        out.print(temp.toString());
				out.flush();
				out.close();
	}
	
	@RequestMapping("/updatepwd")
	public String updatePwd(HttpServletRequest request,HttpServletResponse response,ModelMap map){
		String loginName=request.getParameter("loginName");
		
	 
		SaleUsersLogin saleUser=(SaleUsersLogin)request.getSession().getAttribute("user");
		SaleUsersLogin currentUser=null;
		if(isAgent(request) || saleUser.getLoginName().equals(loginName))
		{
	 
		currentUser=loginService.getUserByLoginName(loginName);
		request.setAttribute("currentUser", currentUser);
		return "users/updatepwd";
		}
		return "users/nopri";
	}
	
	@RequestMapping("/isallow")
	public void isallow(HttpServletRequest request,HttpServletResponse response,ModelMap map) throws IOException{
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		String userStatus=request.getParameter("userStatus");
		String loginName=request.getParameter("loginName");
		
		SaleUsersLogin saleUser=loginService.getUserByLoginName(loginName);
		
		if(!user.getUserName().equals(loginName))
		{
			
			if("y".equals(userStatus))
			{
				saleUser.setUserStatus("n");
				
			}else
			{
				saleUser.setUserStatus("y");
			}
		
		}
		boolean flag=loginService.updateUser(saleUser);
		
		response.setContentType("text/json");
		PrintWriter out=response.getWriter();
		 
			JSONObject jo = new JSONObject();
			jo.put("isDel", flag);
			out.print(jo.toString());
			out.flush();
			out.close();
	}
	
	
	@RequestMapping("/deleteUser/{saleUsersLoginId}")
	public void delete(HttpServletResponse response,@PathVariable("saleUsersLoginId")String saleUsersLoginId) throws IOException
	{
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		boolean flag = loginService.deleteUserById(saleUsersLoginId);
		JSONObject jo = new JSONObject();
		jo.put("isDel", flag);
		out.print(jo);
		out.flush();
		out.close();
		
		
	}
}
